﻿using UnityEngine;
using System.Collections;

namespace Lost{
	/// <summary>
	/// 按键Key，以LostButton为输入，每个按键的值为其Introduction
	/// </summary>
	public class ButtonKey : LockKey {
		public enum ButtonFunction
		{
			Add,Del,Clear,Confirm,Insert,Not
		};

		/// <summary>
		/// 如果返回true，表示希望销毁调用此函数的脚本
		/// </summary>
		/// <param name="btFunc">Bt func.</param>
		/// <param name="BtValue">Bt value.</param>
		public bool OnButtonClicked(ButtonFunction btFunc, string BtValue){
			switch (btFunc) {
			case ButtonKey.ButtonFunction.Add:
				this.AddContent (BtValue);
				break;
			case ButtonKey.ButtonFunction.Del:
				this.DeleteOneLetter ();
				break;
			case ButtonKey.ButtonFunction.Clear:
				this.ClearPassword ();
				break;
			case ButtonKey.ButtonFunction.Confirm:
				int index;
				//失败时index=0
				if (int.TryParse (BtValue, out index)) {
					if (this.UseKey (index)) {
						return true;
					}
				}
				break;
			case ButtonKey.ButtonFunction.Insert:
				this.Insert (BtValue);
				break;
			case ButtonKey.ButtonFunction.Not:
				this.SetNot (BtValue);
				break;
			default:
				break;
			}
			return false;
		}

		public void DeleteOneLetter(){
			int len = CurPassword.Length;
			if (len > 0) {
				CurPassword = CurPassword.Remove (len - 1);
			}
		}
		public void ClearPassword(){
			CurPassword = "";
		}
		public void AddContent(string content){
			CurPassword += content;
		}

		protected override void OnKeyDestroy ()
		{
			base.OnKeyDestroy ();
			LostButton[] bts = GetComponentsInChildren<LostButton> ();
			int len = bts.Length;
			for (int i = 0; i < len; i++) {
				ItemsManager.iDestroy (bts [i]);
			}
		}
		///将content每一个字符以ASCII码顺序插入CurPassword
		public void Insert(string content){
			int cLen = content.Length;
			int pLen = CurPassword.Length;
			int c = 0, p = 0;
			string password = CurPassword;
			for (c = 0; c < cLen; c++) {
				for (p = 0; p < pLen; p++) {
					if (password [p] >= content [c]) {
						if (password [p] > content [c]) {
							password = password.Substring (0, p) + content [c] + password.Substring (p, pLen - p);
							pLen++;
						}
						break;
					}
				}
				if (p == pLen) {
					password += content [c];
				}
			}
			CurPassword = password;
		}
		///取反
		public void SetNot(string content){
			int cLen = content.Length;
			int pLen = CurPassword.Length;
			int c = 0, p = 0;
			string password = CurPassword;
			for (c = 0; c < cLen; c++) {
				for (p = 0; p < pLen; p++) {
					if (password [p] == content [c]) {
						password = password.Remove (p, 1);
						Debug.Log (password);
						pLen--;
						p--;	//不进行这步操作的话就会有p==pLen的bug
						break;
					}
				}
				if (p == pLen) {
					password += content [c];
				}
			}
			CurPassword = password;
		}
	}
}
